package org.feng.service.impl;

import org.feng.base.service.impl.BaseServiceImpl;
import org.feng.mapper.SysSchedulerMapper;
import org.feng.service.ISysSchedulerService;
import org.feng.entity.SysScheduler;
import org.feng.support.SchedulerSupport;
import org.quartz.CronExpression;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;

/**
 * 定时任务表 服务实现类
 *
 * @author : FengShuai
 * @since : 2024/6/27 9:24
 */
@Service
public class SysSchedulerServiceImpl extends BaseServiceImpl<SysSchedulerMapper, SysScheduler> implements ISysSchedulerService {

    @Resource
    private SchedulerSupport schedulerSupport;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateAndRun(SysScheduler sysScheduler) {

        if (!CronExpression.isValidExpression(sysScheduler.getCron())) {
            throw new RuntimeException("定时任务表达式不正确");
        }
        boolean insertedOrUpdate = sysScheduler.insertOrUpdate();
        try {
            schedulerSupport.invoke(sysScheduler);
        } catch (SchedulerException e) {
            throw new RuntimeException("定时任务启动失败", e);
        }
        return insertedOrUpdate;
    }
}

